package admin

import (
	"context"
	"fmt"

	"server/internal/svc"
	"server/internal/types"
	"server/models"
	"server/utils"

	"github.com/zeromicro/go-zero/core/logx"
)

type CategorySelectLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewCategorySelectLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CategorySelectLogic {
	return &CategorySelectLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *CategorySelectLogic) CategorySelect() (resp []types.SelectOptions, err error) {
	datas := make([]models.Category, 0)
	tx := utils.Db.Model(&models.Category{}).Order("level asc")
	utils.TxFind(tx, &datas)
	if len(datas) == 0 {
		return []types.SelectOptions{}, nil
	}

	// 构建权限树
	dataMap := make(map[uint][]models.Category)
	for _, p := range datas {
		// 检查该权限是否在角色对应的动作中
		dataMap[p.ParentID] = append(dataMap[p.ParentID], p)
	}

	// 生成树形结构
	var buildTree func(parentID uint) []types.SelectOptions
	buildTree = func(parentID uint) []types.SelectOptions {
		var nodes []types.SelectOptions
		children, exists := dataMap[parentID]
		if exists {
			for _, child := range children {
				node := types.SelectOptions{
					Value: fmt.Sprintf("%d-%d", child.ParentID, child.ID),
					Label: child.Name,
				}
				children := buildTree(child.ID)
				if len(children) > 0 {
					node.Children = children
				} else {
					node.Children = []types.SelectOptions{}
				}
				nodes = append(nodes, node)
			}
		}
		return nodes
	}

	resp = buildTree(0)
	return resp, nil
}
